package net.shenru.ui.encog;

import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Attributes;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import net.shenru.BaseActivity;
import net.shenru.R;
import net.shenru.encogs.EncogTask;
import net.shenru.encogs.EncogType;
import net.shenru.os.utlis.SrLog;
import net.shenru.os.utlis.UniqueIdGenerator;
import net.shenru.server.EncogServer;
import net.shenru.server.ServerFactory;
import net.shenru.server.ServerType;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.HttpAuthHandler;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebStorage.QuotaUpdater;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 抓取bus信息
 */
public class EncogBusActivity extends BaseActivity {

	protected static final String TAG = EncogBusActivity.class.getSimpleName();

	private EncogTask encogTask;

	// <dt>按首字母查看:</dt>
	// <dd>
	// <span class="red">1</span>
	// <a href="/sitemap1/2/">2</a>
	// <a href="/sitemap1/3/">3</a>
	// <a href="/sitemap1/4/">4</a>
	// <a href="/sitemap1/5/">5</a>
	// <a href="/sitemap1/6/">6</a>
	// <a href="/sitemap1/7/">7</a>
	// <a href="/sitemap1/8/">8</a>
	// <a href="/sitemap1/9/">9</a>
	// <a href="/sitemap1/B/">B</a>
	// <a href="/sitemap1/C/">C</a>
	// <a href="/sitemap1/D/">D</a>
	// <a href="/sitemap1/F/">F</a>
	// <a href="/sitemap1/H/">H</a>
	// <a href="/sitemap1/J/">J</a>
	// <a href="/sitemap1/K/">K</a>
	// <a href="/sitemap1/L/">L</a>
	// <a href="/sitemap1/M/">M</a>
	// <a href="/sitemap1/P/">P</a>
	// <a href="/sitemap1/Q/">Q</a>
	// <a href="/sitemap1/S/">S</a>
	// <a href="/sitemap1/T/">T</a>
	// <a href="/sitemap1/Y/">Y</a>
	// </dd>
	// </dl>

	private WebView webView;
	private static ArrayList<String> urls = new ArrayList<String>();
	static {
		urls.add("http://bj.bus.58.com/sitemap1/1/");
		urls.add("http://bj.bus.58.com/sitemap1/2/");
		urls.add("http://bj.bus.58.com/sitemap1/3/");
		urls.add("http://bj.bus.58.com/sitemap1/4/");
		urls.add("http://bj.bus.58.com/sitemap1/5/");
		urls.add("http://bj.bus.58.com/sitemap1/6/");
		urls.add("http://bj.bus.58.com/sitemap1/7/");
		urls.add("http://bj.bus.58.com/sitemap1/8/");
		urls.add("http://bj.bus.58.com/sitemap1/9/");
		urls.add("http://bj.bus.58.com/sitemap1/B/");
		urls.add("http://bj.bus.58.com/sitemap1/C/");
		urls.add("http://bj.bus.58.com/sitemap1/D/");
		urls.add("http://bj.bus.58.com/sitemap1/F/");
		urls.add("http://bj.bus.58.com/sitemap1/H/");
		urls.add("http://bj.bus.58.com/sitemap1/J/");
		urls.add("http://bj.bus.58.com/sitemap1/K/");
		urls.add("http://bj.bus.58.com/sitemap1/L/");
		urls.add("http://bj.bus.58.com/sitemap1/M/");
		urls.add("http://bj.bus.58.com/sitemap1/P/");
		urls.add("http://bj.bus.58.com/sitemap1/Q/");
		urls.add("http://bj.bus.58.com/sitemap1/S/");
		urls.add("http://bj.bus.58.com/sitemap1/T/");
		urls.add("http://bj.bus.58.com/sitemap1/Y/");
		// urls.add("http://bus.mapbar.com/beijing/line_list/");
		// urls.add("http://bus.mapbar.com/beijing/line_list/Y.shtml");
		// urls.add("http://bus.aibang.com/bus/beijing/line_1.html");
		// urls.add("http://beijing.8684.cn/sitemap");
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == 1) {
				WebView view = (WebView) msg.obj;
				// view.loadUrl("javascript:window.local_obj.showSource('<head>'+"
				// +
				// "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
				view.loadUrl("javascript:window.local_obj.showSource(document.body.innerHTML);");

			} else if (msg.what == 0) {
				String url = (String) msg.obj;
				if (url != null) {
					SrLog.i(TAG, "加载下一个url" + url);
					webView.loadUrl(url);
				}
			}

		}

	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_webview);
		webView = (WebView) findViewById(R.id.webview);
		webView.getSettings().setJavaScriptEnabled(true);
		// 添加一个类到javascript
		webView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
		webView.setWebViewClient(new MyWebViewClient());
		loadNextUrl();
	}

	final class MyWebViewClient extends WebViewClient {
		// public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// // Log.d(TAG, "url:" + url);
		// view.loadUrl(url);
		// return true;
		// }

		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d("WebView", "onPageStarted");
			super.onPageStarted(view, url, favicon);
		}

		public void onPageFinished(WebView view, String url) {
			Log.d("WebView", "onPageFinished ");
			// 显示html两种脚本
			// view.loadUrl("javascript:window.local_obj.showSource('<head>'+"
			// +
			// "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
			view.loadUrl("javascript:window.local_obj.showSource(document.body.innerHTML);");
			super.onPageFinished(view, url);
			loadNextUrl();
		}

	}

	// 加载下一个网页
	private void loadNextUrl() {
		String nextUrl = nextUrl();
		if (nextUrl != null) {
			mHandler.obtainMessage(0, nextUrl).sendToTarget();
		}
	}

	// 得到下一个网页
	private int index = 0;

	private synchronized String nextUrl() {
		int size = urls.size();
		if (size > index) {
			String result = urls.get(index);
			++index;
			return result;
		}
		return null;
	}

	// 添加到javascript类，提用她输出结果
	final class InJavaScriptLocalObj {
		public void showSource(String html) {
			// 这里注意Log打印有个数显示，sysout打印没有个数限制。个数就是缓存区Log在打印超过很多子显示不出来
			// Log.d("HTML", html);
			// System.out.println(html);
			Log.d("HTML", "===================================================");
			parset(html);
		}
	}

	//解析html
	//<html><ul><a href=\"http://bj.bus.58.com/x_te3lu/\" title=\"特3路\">特3路</a></li></ul></html>
	private void parset(String html) {
		Source source = new Source(html);
		List<Element> allElements = source.getAllElements("li");
		for (Element element : allElements) {
			List<Element> aElements = element.getAllElements("a");
			for (Element a : aElements) {
				Attributes attributes = a.getAttributes();
				System.out.println(attributes);
			}
		}
	}

	// ====================================================================================================
	private void EncogBus() {
		EncogServer encogServer = (EncogServer) ServerFactory.getServer(getApplicationContext(), ServerType.Encog);
		if (encogServer.getTask() == null) {
			encogTask = new EncogTask(UniqueIdGenerator.getInstance().getLongId());
			encogTask.setStartUrl("http://bus.mapbar.com/beijing/line_list/");
			encogTask.setSingle(true);
			// encogTask.setLabel("公交");
			encogTask.setType(EncogType.Bus);
			encogServer.setTaskBus(encogTask);
			encogServer.run();
		}
		// 开始url
		// 第一步抓取所有url
		// ---抓取标签
		// ---http://bus.mapbar.com/beijing/xianlu/ping35ludonggou/
		// ---
		// 第二步匹配url
	}
}
